import { message } from 'antd';
import Cookies from 'js-cookie';
import { history } from 'umi';

import type { RequestConfig } from 'umi';

export const request: RequestConfig = {
  requestInterceptors: [
    (url, options) => {
      const uri = `${BASE_URL_API}${url}`;
      const token = Cookies.get('saas_token');

      if (token) {
        const headers = {
          Authorization: `${token}`,
        };
        return {
          url: uri,
          options: { ...options, headers },
        };
      }
      return { url: uri, options };
    },
  ],
  responseInterceptors: [
    async (response) => {
      if (response.status === 500) {
        message.error('服务器错误, 稍后尝试！');
      }
      const contentType = response.headers.get('Content-Type');
      if (contentType === 'application/json') {
        const data = await response.clone().json();
        if (data && data.code === 401) {
          Cookies.remove('saas_token');
          history.replace('/login');
        }
      }
      return response;
    },
  ],
};

export async function getInitialState(): Promise<{
  id?: string;
  companyName?: string;
  name?: string;
  departmentName?: string;
}> {
  const initData: Record<string, any> = {};
  console.log('初始化');
  return initData;
}

// 全局处理-每隔12小时页面进行重新加载
const timerGlobal = setTimeout(() => {
  clearTimeout(timerGlobal);
  window.location.reload();
}, 1000 * 60 * 60 * 12);
